package com.guocheng.modules.login.controller;

import com.guocheng.base.BaseController;
import com.guocheng.entity.AjaxResult;
import com.guocheng.modules.login.model.dto.UserDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController extends BaseController {

    @GetMapping(value = "/login",name = "登录页面")
    public String login(){
        if(user!=null){
            return "redirect:/index";
        }
        return "login";
    }

    /**
     * 登录逻辑处理
     */
    @PostMapping(value = "/login",name = "用户登录")
    @ResponseBody
    public AjaxResult login(UserDTO userDTO){
        if(user!=null){
            return AjaxResult.error("请输入用户名");
        }
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUsername(),userDTO.getPassword());
        try {
            //3.执行登录方法
            subject.login(token);
            //登录成功
            session.setAttribute("loginUser",subject.getPrincipals().getPrimaryPrincipal());

            return AjaxResult.ok("登入成功");
        } catch (UnknownAccountException e) {
            //登录失败:用户名不存在，UnknownAccountException是Shiro抛出的找不到用户异常
            return AjaxResult.error("用户名不存在");
        }catch (IncorrectCredentialsException e) {
            //登录失败:密码错误，IncorrectCredentialsException是Shiro抛出的密码错误异常
            return AjaxResult.error("密码错误");
        }
    }

    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
        session.setAttribute("loginUser",null);
        user=null;
        SecurityUtils.getSubject().logout();   //登出
        return "redirect:/login";
    }

}
